<?php


function sendMailNEW($post_data) {
	Vendor('phpMailer.PHPMailerAutoload');
	// 实例化PHPMailer核心类
	$mail = new PHPMailer();
	// 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
	$mail->SMTPDebug = 1;
	// 使用smtp鉴权方式发送邮件
	$mail->isSMTP();
	// smtp需要鉴权 这个必须是true
	$mail->SMTPAuth = true;
	// 链接qq域名邮箱的服务器地址
	$mail->Host =$post_data['mail_host'];
	// 设置使用ssl加密方式登录鉴权
	$mail->SMTPSecure = 'ssl';
	// 设置ssl连接smtp服务器的远程服务器端口号
	$mail->Port =$post_data['mail_port'];
	// 设置发送的邮件的编码
	$mail->CharSet = 'UTF-8';
	// 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
	$mail->FromName  = $post_data['mail_name'];
	// smtp登录的账号 QQ邮箱即可
	$mail->Username =$post_data['mail_account'];
	// smtp登录的密码 使用生成的授权码
	$mail->Password =$post_data['mail_pass'];
	// 设置发件人邮箱地址 同登录账号
	$mail->From =$post_data['mail_account'];
	// 邮件正文是否为html编码 注意此处是一个方法
	$mail->isHTML(true);
	// 设置收件人邮箱地址
	$mail->addAddress($post_data['mail_to']);
	// 添加多个收件人 则多次调用方法即可
	//$mail->addAddress('852986690@qq.com');
	// 添加该邮件的主题
	$mail->Subject = $post_data['mail_subject'];
	// 添加邮件正文
	$mail->Body =  $post_data['mail_content'];
	// 为该邮件添加附件
	// $mail->addAttachment('./example.pdf');
	// 发送邮件 返回状态
	  return (bool)($mail->send());

}

function getTicketzt($id){
	switch ($id)
	{
	case 1:
		$str = "待您反馈";
		break;
	case 2:
		$str = "已关闭";
		break;
	default:
		$str = "等待回复";
	}

	return $str;
}
function base62($x)

{

$show= '';

 while($x> 0) {

$s= $x% 62;

if($s> 35) {

$s= chr($s+61);

} elseif($s> 9 && $s<=35) {

$s= chr($s+ 55);

}

$show.= $s;

 $x= floor($x/62);

}

return $show;

}
function urlShort($url)

{

$url= crc32($url);

$result= sprintf("%u", $url);

return base62($result);

 }


function get_client_ipaddress($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下，获取客户端真实IP
        $ip=$_SERVER['HTTP_X_REAL_IP'];
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
    }else{
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
 }

/* 截取udid */
function str_to($str){
	if (!empty($str)) {
		return substr($str,0,4).'****'.substr($str,-4);
	} else {
		return '';
	}
}

/* 获取用户名称 */
function getName($uid){
	if (!empty($uid)) {
		$member = M('Member');
		$username = $member->where(array('id'=>$uid))->getField('username');
		return $username;
	} else {
		return '';
	}
}

/* 获取用户ID */
function getId($username){
	if (!empty($username)) {
		$member = M('Member');
		$id = $member->where(array('username'=>$username))->getField('id');
		return $id;
	} else {
		return '';
	}
}

//判断是否为字典数组（dict）
function isDict($array)
{
 return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));

}

//向xml节点中写入字典数组（dict）
function xmlWriteDict(XMLWriter $x, &$dict)
{
 $x->startElement('dict');
 foreach($dict as $k => &$v)
 {
 $x->writeElement('key', $k);
 xmlWriteValue($x, $v);
 }
 $x->endElement();
}

 //向xml节点中写入数组（array）
function xmlWriteArray(XMLWriter $x, &$arr)
{
 $x->startElement('array');
 foreach($arr as &$v)
 xmlWriteValue($x, $v);
 $x->endElement();
}

//根据类型向xml节点中写入值
function xmlWriteValue(XMLWriter $x, &$v)
{
 if (is_int($v) || is_long($v))
 $x->writeElement('integer', $v);
 elseif (is_float($v) || is_real($v) || is_double($v))
 $x->writeElement('real', $v);
 elseif (is_string($v))
 $x->writeElement('string', $v);
 elseif (is_bool($v))
 $x->writeElement($v?'true':'false');
 elseif (isDict($v))
 xmlWriteDict($x, $v);
 elseif (is_array($v))
 xmlWriteArray($x, $v);
 else
 {
 trigger_error("Unsupported data type in plist ($v)", E_USER_WARNING);
 $x->writeElement('string', $v);
 }
}
//add by cq : 联系我 ：18211436586
function GetIphonePlistInfo($ipafile,$pAttr){
$attResult ='';
	try {
		$Client=new SoapClient("http://localhost:8096/GetIphoneInfo.asmx?wsdl",array('encoding'=>'utf-8'));

	 if($Client){
			//解决中文乱码问题
			 $Client->soap_defencoding = 'utf-8';
			 $Client->decode_utf8 = false;
			 $Client->xml_encoding = 'utf-8';
			 $param=array('attr'=>$pAttr,'ipaAddress'=> $ipafile);
			 try{
					 $result=$Client->__soapCall("GetIphonePlistInfo",array("parameters"=>$param));
						$attResult = $result->GetIphonePlistInfoResult;
			 }catch(Exception $e){
			 }
	 }
	} catch (SOAPFault $e) {
			 $attResult = '';
	}
return  array_iconv($attResult);
}

function GetAPPpackageInfo($appAddress,$iconAddress)
{
	$http='http://localhost:8006/AppPackageInfo/services/AppInfo?wsdl';
	$client = new SoapClient($http,array('encoding'=>'utf-8'));
	$param=array('appAddress'=>$appAddress, 'iconAddress'=>$iconAddress);
	$client->soap_defencoding = 'utf-8';
	$client->xml_encoding = 'utf-8';
	$result=$client->__soapCall("obtainAppInfo",array("parameters"=>$param));
	return $result->obtainAppInfoReturn;
}

function array_iconv($data, $output = 'utf-8') {
  $encode_arr = array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
  $encoded = mb_detect_encoding($data, $encode_arr);
  if (!is_array($data)) {
    return mb_convert_encoding($data, $output, $encoded);
  }
  else {
    foreach ($data as $key=>$val) {
      $key = array_iconv($key, $output);
      if(is_array($val)) {
        $data[$key] = array_iconv($val, $output);
      } else {
      $data[$key] = mb_convert_encoding($data, $output, $encoded);
      }
    }
  return $data;
  }
}

//创建plist
function createplist($ctlist)
{
 $title = $ctlist['title'];
 $subtitle = $ctlist['subtitle'];
 $versionname = $ctlist['versionname'];
 $bundle_identifier = $ctlist['bundle_identifier'];
 $ssl_server = $ctlist['ssl_server'];
 $channelid = $ctlist['cid'];
 $iconurl = $ctlist['icon'];
 if (!$versionname)
 {
 $versionname = '6.0.0';
 }
 $versioncode = str_replace('.', '', $versionname);

 if (!$channelid)
 {
 $channelid = '0';
 }

 header('Content-Type: application/xml');
 $plist = new XmlWriter();
 $plist->openMemory();
 $plist->setIndent(TRUE);
 $plist->startDocument('1.0', 'UTF-8');
 $plist->writeDTD('plist', '-//Apple//DTD PLIST 1.0//EN', 'http://www.apple.com/DTDs/PropertyList-1.0.dtd');
 $plist->startElement('plist');
 $plist->writeAttribute('version', '1.0');

 $pkg = array();
 $pkg['kind'] = 'software-package';

 $member = M('Member');
 $uptype = $member->where(array('id'=>session('homeId')))->getField('uptype');
 if ($uptype == 1) {
   $pkg['url'] = $channelid;
 } elseif ($uptype == 2) {
   $pkg['url'] =  $channelid;
 }


 $displayimage = array();
 $displayimage['kind'] = 'display-image';
 $displayimage['needs-shine'] = TRUE;
 $displayimage['url'] = $iconurl;

 $fullsizeimage = array();
 $fullsizeimage['kind'] = 'full-size-image';
 $fullsizeimage['needs-shine'] = TRUE;
 $fullsizeimage['url'] = $iconurl;

 $assets = array();
 $assets[] = $pkg;
 $assets[] = $displayimage;
 $assets[] = $fullsizeimage;

 $metadata = array();
 $metadata['bundle-identifier'] = $bundle_identifier;
 $metadata['bundle-version'] = $versionname;
 $metadata['kind'] = 'software';
 $metadata['subtitle'] = $subtitle;
 $metadata['title'] = $title;

 $items0 = array();
 $items0['assets'] = $assets;
 $items0['metadata'] = $metadata;

 $items = array();
 $items[] = $items0;

 $root = array();
 $root['items'] = $items;

 xmlWriteValue($plist, $root);

 $plist->endElement();
 $plist->endDocument();

 return $plist->outputMemory();
}

	/**
     * 解析XML格式的字符串
     *
     * @param string $str
     * @return 解析正确就返回解析结果,否则返回false,说明字符串不是XML格式
     */
    function xml_parser($str){
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$str,true)){
            xml_parser_free($xml_parser);
            return false;
        }else {
            return (json_decode(json_encode(simplexml_load_string($str)),true));
        }
    }

function deldir($dir) {
    //先删除目录下的文件：
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
    	if($file!="." && $file!="..") {
        	$fullpath=$dir."/".$file;
      		if(!is_dir($fullpath)) {
          		unlink($fullpath);
      		} else {
          		deldir($fullpath);
      		}
    	}
  	}

  	closedir($dh);
  	//删除当前文件夹：
  	if(rmdir($dir)) {
    	return true;
  	} else {
    	return false;
  	}
}

//php文件大小单位转换GB MB KB
function formatBytes($size) {
  $units = array(' B', ' KB', ' MB', ' GB', ' TB');
  for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
  return round($size, 2).$units[$i];
 }

function formatBytesMb($size) {
  $size = $size/1024/1024;
  return round($size, 2);
 }

 //获取用户过期时间
 function gqtime($id) {
  $member = M('Member');
  $list = $member->where(array('id'=>$id))->field('create_time,tianshu')->find();
  return ($list['create_time']  + ($list['tianshu'] * 24 * 60 * 60));
}


function is_mobile(){

	// returns true if one of the specified mobile browsers is detected
	// 如果监测到是指定的浏览器之一则返回true

	$regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";

   $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";

	$regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";

	$regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";

	$regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";

	$regex_match.=")/i";

	// preg_match()方法功能为匹配字符，既第二个参数所含字符是否包含第一个参数所含字符，包含则返回1既true
	return preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
}
